package com.amuji.adiaosexpense.db;

import java.util.ArrayList;
import java.util.List;

import com.amuji.adiaosexpense.domainObjs.Person;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PersonsDataSource {
  // Database fields
  private SQLiteDatabase database;
  private PersonSQLiteHelper dbHelper;
  private String[] allColumns = { 
      PersonSQLiteHelper.COLUMN_ID, 
      PersonSQLiteHelper.COLUMN_FIRST_NAME, 
      PersonSQLiteHelper.COLUMN_LAST_NAME };

  public PersonsDataSource(Context context) {
    dbHelper = new PersonSQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public Person createPerson(Person person) {
    ContentValues values = new ContentValues();
    values.put(PersonSQLiteHelper.COLUMN_FIRST_NAME, person.getFirstName());
    values.put(PersonSQLiteHelper.COLUMN_LAST_NAME, person.getLastName());
    
    long insertId = database.insert(PersonSQLiteHelper.TABLE_PERSONS, null, values);
    Cursor cursor = database.query(PersonSQLiteHelper.TABLE_PERSONS, allColumns, PersonSQLiteHelper.COLUMN_ID + " = "
        + insertId, null, null, null, null);
    cursor.moveToFirst();
    Person result = cursorToPerson(cursor);
    cursor.close();
    return result;
  }

  public void delete(Person person) {
    long id = person.getId();
    database.delete(PersonSQLiteHelper.TABLE_PERSONS, PersonSQLiteHelper.COLUMN_ID + " = " + id, null);
    Log.w(PersonsDataSource.class.getName(), "Removed person: " + person.toString());
  }

  public List<Person> getAll() {
    List<Person> persons = new ArrayList<Person>();

    Cursor cursor = database.query(PersonSQLiteHelper.TABLE_PERSONS, allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Person person = cursorToPerson(cursor);
      persons.add(person);
      cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return persons;
  }

  private Person cursorToPerson(Cursor cursor) {
    Person person = new Person();
    person.setId(cursor.getLong(0));
    person.setFirstName(cursor.getString(1));
    person.setLastName(cursor.getString(2));
    return person;
  }
}
